package com.xiguthings.waka.web.controller.question;

import com.github.pagehelper.PageHelper;
import com.xiguthings.waka.dao.DataBaseStatus;
import com.xiguthings.waka.exception.BussinessException;
import com.xiguthings.waka.po.Paper;
import com.xiguthings.waka.po.PaperExample;
import com.xiguthings.waka.po.PaperQuestion;
import com.xiguthings.waka.po.PaperQuestionExample;
import com.xiguthings.waka.po.extpo.Page;
import com.xiguthings.waka.publicUtils.StringUtils;
import com.xiguthings.waka.service.question.IPaperQuestionService;
import com.xiguthings.waka.web.controller.base.AbstractController;
import com.xiguthings.waka.web.controller.base.ResponseEntity;
import com.xiguthings.waka.web.controller.paper.PaperVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/paperquestion")
@Api(tags = "试题")
public class PaperQuestionController extends AbstractController {
    @Resource
    private IPaperQuestionService paperQuestionService;

    /**
     * 判断paperVo 如果是空的，报出异常
     *
     * @param paperQuestionVo
     */
    private void ifEmptyVo(PaperQuestionVo paperQuestionVo, String msg) {
        if (paperQuestionVo == null || paperQuestionVo.getPaperQuestion() == null) {
            throwCodeEmptyException(msg);
        }
    }


    /**
     * 创建查询条件
     *
     * @param paperQuestionVo
     * @param example
     * @throws NumberFormatException
     */
    private void queryConditions(PaperQuestionVo paperQuestionVo, PaperQuestionExample example) throws NumberFormatException {

        PaperQuestionExample.Criteria criteria = example.createCriteria();
        // 如果查询条件为空的
        if (paperQuestionVo == null) {
            // 则查询所有未被删除的
            criteria.andStatusNotEqualTo(DataBaseStatus.DELETE);
            return;
        }

        // 如果有查询条件
        PaperQuestion papaerQuestion = paperQuestionVo.getPaperQuestion();
        // 添加查询条件
        if (papaerQuestion != null) {
            if (StringUtils.isNotBlank(papaerQuestion.getQuestionId())) {
                criteria.andQuestionIdEqualTo(papaerQuestion.getQuestionId());
            }
            if (StringUtils.isNotBlank(papaerQuestion.getPaperId())) {
                criteria.andPaperIdEqualTo(papaerQuestion.getPaperId());
            }
            if (StringUtils.isNotBlank(papaerQuestion.getQuestionContent())) {
                criteria.andQuestionContentLike("%" + papaerQuestion.getQuestionContent() + "%");
            }
            if (papaerQuestion.getRank() != null) {
                criteria.andRankEqualTo(papaerQuestion.getRank());
            }
        }

        if (StringUtils.isNotBlank(paperQuestionVo.getInStatus())) {
            // 添加包含的状态
            String statuses = paperQuestionVo.getInStatus();
            String[] statusArr = statuses.split(",");
            List<Integer> statusList = new ArrayList<>();
            for (String str : statusArr) {
                statusList.add(new Integer(str));
            }
            criteria.andStatusIn(statusList);
        } else {
            // 如果状态的查询条件是空的，则查询没有被删除的
            criteria.andStatusNotEqualTo(DataBaseStatus.DELETE);
        }


    }


    /**
     * 修改或者添加
     *
     * @param paperQuestionVo
     * @return
     * @throws Exception
     */
    @ApiOperation(tags = {
            "1.控制台"}, value = "修改/添加", httpMethod = "POST", notes = "修改时，必须填写“paperQuestion.questionId”参数。<br>添加新记录时，paperId、questionContent、rank是必填的", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paperQuestion.questionId", value = "主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paperQuestion.paperId", value = "所属的试卷的的主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paperQuestion.questionContent", value = "问题的具体内容", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paperQuestion.rank", value = "试卷的排序号，数字小的排在前面", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paperQuestion.status", value = "状态：0--正常，99--删除", dataType = "int", required = false, paramType = "query")})
    @RequestMapping("/save")
    @ResponseBody
    public ResponseEntity save(@ApiIgnore PaperQuestionVo paperQuestionVo) throws Exception {
        ifEmptyVo(paperQuestionVo, null);
        PaperQuestion paperQuestion = paperQuestionVo.getPaperQuestion();
        String questionId = paperQuestion.getQuestionId();
        String msg = null;
        if (StringUtils.isNotBlank(questionId)) {
            // 修改
            int row = paperQuestionService.updateByPrimaryKeySelective(paperQuestion);
            if (row > 0) {
                msg = "修改成功";
            } else {
                msg = "修改失败，可能数据库中不存在这条数据";
            }
        } else {
            // 添加
            msg = "添加成功";
            paperQuestionService.insert(paperQuestion);
        }
        return ajaxReturnMap(CODE_SUCCESS, msg, questionId);
    }

    @ApiOperation(tags = {"1.控制台",
            "2.用户端"}, value = "根据主键获取记录详情", httpMethod = "GET", notes = "questionId是必填", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "papaerQuestion.questionId", value = "主键id", dataType = "String", required = true, paramType = "query"),
//            @ApiImplicitParam(name = "associated", value = "是否关联查询,true--关联查询,默认是false", dataType = "boolean", required = false, paramType = "query")
    })
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseEntity detail(@ApiIgnore PaperQuestionVo paperQuestionVo) throws Exception {
        String errMsg = "questionId为空";
        ifEmptyVo(paperQuestionVo, errMsg);
        String id = paperQuestionVo.getPaperQuestion().getQuestionId();
        if (StringUtils.isBlank(id)) {
            BussinessException.throwThis(CODE_EMPTY_REQUIRED, errMsg);
        }

        PaperQuestion paperQuestion = paperQuestionService.selectByPrimaryKey(id);
        return ajaxReturnMap(CODE_SUCCESS, null, paperQuestion);
    }

    @ApiOperation(tags = {"1.控制台",
            "2.用户端"}, value = "删除记录", httpMethod = "GET", notes = "questionId是必填", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paperQuestion.questionId", value = "主键id", dataType = "String", required = true, paramType = "query")})
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseEntity delete(@ApiIgnore PaperQuestionVo paperQuestionVo) throws Exception {
        String errMsg = "questionId为空";
        ifEmptyVo(paperQuestionVo, errMsg);
        PaperQuestion paperQuestion = paperQuestionVo.getPaperQuestion();
        String questionId = paperQuestion.getQuestionId();
        if (StringUtils.isBlank(questionId)) {
            BussinessException.throwThis(CODE_EMPTY_REQUIRED, errMsg);
        }

        int row = paperQuestionService.deleteByPrimaryKey(questionId);
        String msg = null;
        if (row > 0) {
            msg = "删除成功";
        } else {
            msg = "删除失败，可能数据库中不存在这条数据";
        }

        return ajaxReturnMap(CODE_SUCCESS, msg, null);
    }

    /**
     * 分页查询
     *
     * @param paperQuestionVo
     * @param page
     * @return
     * @throws Exception
     */

    @ApiOperation(tags = {"1.控制台",
            "2.用户端"}, value = "分页查询", httpMethod = "GET", notes = "可根据条件进行筛选", response = ResponseEntity.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "paperQuestion.questionId", value = "主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paperQuestion.paperId", value = "所属的试卷的的主键id", dataType = "String", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paperQuestion.questionContent", value = "问题的具体内容", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "paperQuestion.rank", value = "试卷的排序号，数字小的排在前面", dataType = "string", required = false, paramType = "query"),
            @ApiImplicitParam(name = "inStatus", value = "状态：0--正常，99--删除", dataType = "int", required = false, paramType = "query"),
//            @ApiImplicitParam(name = "associated", value = "是否关联查询,true--关联查询,默认是false", dataType = "boolean", required = false, paramType = "query"),
            @ApiImplicitParam(name = "page", value = "页码，如果没有值，则使用默认值。开始值从 1 开始计算", dataType = "int", required = false, paramType = "query"),
            @ApiImplicitParam(name = "rows", value = "每页的数量,如果没有值，则使用默认值", dataType = "int", required = false, paramType = "query")})
    @RequestMapping("/pagelist")
    @ResponseBody
    public ResponseEntity pageList(@ApiIgnore PaperQuestionVo paperQuestionVo, @ApiIgnore Page page) throws Exception {
        PaperQuestionExample example = new PaperQuestionExample();
        // 创建查询条件
        queryConditions(paperQuestionVo, example);
        super.selectByPage(page, example, paperQuestionService);
        return ajaxReturnMap(CODE_SUCCESS, null, page);
    }

}
